package com.tunnel.service.hendler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.util.CharsetUtil;
import io.netty.channel.ChannelFutureListener;

public class MyHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        // 响应体
        String responseBody = "Hello, World!";

        // 构建HTTP响应
        String response = "HTTP/1.1 200 OK\r\n" +
                "Content-Type: text/plain; charset=UTF-8\r\n" +
                "Content-Length: " + responseBody.length() + "\r\n" +
                "Date: Mon, 11 Nov 2024 03:37:12 GMT\r\n" +
                "Keep-Alive: timeout=60\r\n" +
                "Connection: keep-alive\r\n" +
                "\r\n" +
                responseBody;

        // 将响应转换为ByteBuf
        ByteBuf byteBuf = Unpooled.copiedBuffer(response, CharsetUtil.UTF_8);

        // 发送响应
        ctx.writeAndFlush(byteBuf).addListener(ChannelFutureListener.CLOSE);
    }



    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}
